# 
# for_ferret_support.rb
# 
# Created on 21/09/2007, 17:32:10
# 

module AutoRest  
module DefaultMethods

  module Search

    # A route for :collection => { :search => :get } should be in place.
    def search options= {}

      @query= ar_transform_query_terms(params[:query_terms])

      if !@query.empty?
        options[:page]||= (params[:page] || 1)
        options[:limit]||= ardata.ferret.options[:search_limit]

        # Search is implemented regardless of the parent: we don't limit
        # the search result to a specific parent object (though this can
        # be changed through the options via a ar option {:condition => ...}
        model= ardata.resource.model

        if ardata.will_paginate.enabled
          @search_results= model.paginate_search(@query, options)
        else
          @search_results= model.find_by_contents(@query, options)
        end
      end

      respond_to do |format|
        format.html { render ardata.templates.search }
        format.js   { render ardata.templates.search_results }
        format.xml  { render :xml => (@search_results || []).to_xml }
      end
    end

  private

    # By default, if user did a "hello world" search, 
    # change it to a "*hello* or *world*" search
    def ar_transform_query_terms terms
      if terms && !terms.empty? && terms !~ /^\s*[*? ]*\s*$/
        terms.split(" ").inject([]) do |query, token| 
          query << "*#{token}*" 
        end.join(" or ")
      else
        ""
      end
    end
  end #module FerretSupport
  
end #module RestClassMethods
end #module AutoRest  